import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import Drawer from '@/components/drawer/Index'
import FilterRender from '@/render/FilterRender'
import { Button, message } from 'ant-design-vue'
import { LinkOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import RenderDescription, { type DescItemDto } from '@/components/render-descriotion/Index'
import renderModal, {
    getModelValue,
    initModelValue,
    type FormModalDto
} from '@/components/modal/Modal'
import type { InsureCompanyOccupationDto, InsureOccupationDto } from '@/api/insureIndustry/types'
import { AllowStatusCnEnum, getKeyToEnum, OccupationLevelCnEnum } from '@/const/enum'
import { addCompanyOccupation, deleteCompanyOccupation, editCompanyOccupation, queryCompanyOccupationListByOccupationId } from '@/api/insureIndustry'
import type { AddType } from '@/api/types'
import { confirm } from '@/utils/util'

type TemplateType = {
    [key: string]: {
        label: string
        value: string | number,
        span?: number
    }
}

@Component
export class EditInsuranceCompanyPop extends FilterRender {
    @Prop() show!: boolean
    @Prop() curData!: InsureOccupationDto

    showDrawer = false
    addCounter = 0

    addType = 'add' as AddType

    currentIndex = 0
    association = [] as DescItemDto[][]

    occupationList = [] as InsureCompanyOccupationDto[]
    curOccupation = {} as InsureCompanyOccupationDto

    @Emit('update:show')
    updateShow(val: boolean) {
        return val
    }

    @Emit('change')
    handleChange() {
        return
    }

    @Watch('show', { immediate: true })
    handleWatchShow(newval: boolean) {
        this.showDrawer = newval
        this.show && this.initOccupationList()
    }

    @Watch('showDrawer', { immediate: true })
    handleWatchShowDialog() {
        this.updateShow(this.showDrawer)
    }

    // 模板
    associationTemplate = {
        insureCompanyCode: {
            label: '保司名称',
            value: ''
        },
        code: {
            label: '保司编码',
            value: ''
        },
        originLevel: {
            label: '原风险等级',
            value: '',
        },
        highRisk: {
            label: '是否高危',
            value: ''
        },
        originName: {
            label: '保司工种',
            value: '',
            span: 2
        }
    } as TemplateType

    formConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '添加关联保司',
            width: '450px',
            theme: 'dark',
            show: false,
            labelCol: {
                style: {
                    width: '8em'
                }
            },
            params: {
                confirmText: '确定'
            },
            items: {
                insureCompanyCode: {
                    name: '保司名称',
                    element: 'select',
                    optionsType: 'insureCompany',
                    required: true
                },
                originName: {
                    name: '工种名称',
                    element: 'input',
                    required: true
                },
                code: {
                    name: '工种编码',
                    element: 'input',
                    required: true
                },
                originLevel: {
                    name: '原风险等级',
                    element: 'select',
                    required: true,
                    options: getKeyToEnum(OccupationLevelCnEnum)
                },
                highRisk: {
                    name: '是否高危',
                    element: 'select',
                    options: getKeyToEnum(AllowStatusCnEnum)
                }
            },
            complete: async () => {
                const data = getModelValue(this.formConfig)
                data.industryId = this.curData.industryId
                data.occupationId = this.curData.id
                if (this.addType === 'add') {
                    await addCompanyOccupation(data)
                } else {
                    data.id = this.curOccupation.id
                    data.insureCompanyCode = this.curOccupation.insureCompanyCode
                    await editCompanyOccupation(data)
                }
                this.onClose()
            },
            cancel: () => {
                this.onClose()
            }
        } as FormModalDto
    }

    onClose() {
        this.formConfig.show = false
        initModelValue(this.formConfig)
        this.initOccupationList()
    }

    // 提交
    async onSubmit() {
        this.showDrawer = false
        this.handleChange()
    }

    get systemInfoData() {
        return [
            {
                label: '系统行业',
                value: this.curData.industryName
            },
            {
                label: '系统等级',
                slot: () => {
                    return <div>{this.curData.level}类</div>
                }
            },
            {
                label: '系统工种',
                value: this.curData.name
            },
            {
                label: '工种编码',
                value: this.curData.code
            }
        ] as DescItemDto[]
    }



    async onDelAssociationItem(index: number) {
        await confirm('确定删除吗？', '提示')
        deleteCompanyOccupation(this.occupationList[index].id)
        message.success('删除成功')
        this.initOccupationList()
    }
    // 添加
    onOpenAddAssociation() {
        this.addType = 'add'
        this.formConfig.title = '添加关联保司'
        this.formConfig.show = true
    }
    // 数据清洗后添加
    addAssociation(event: InsureCompanyOccupationDto) {
        const data = [] as DescItemDto[]
        for (const key in this.associationTemplate) {
            data.push({
                ...this.associationTemplate[key],
                value: event[key as keyof typeof event],
                key: key
            })
        }
        this.association.push(data)
        this.addCounter++
    }
    // 点击编辑
    onEditInsuranceCompany(index: number) {
        this.addType = 'edit'
        this.currentIndex = index
        this.curOccupation = this.occupationList[index]
        const obj: Record<string, any> = {}
        this.association[index].forEach((item) => {
            if (item.key !== undefined) {
                obj[item.key] = item.value
            }
        })
        initModelValue(this.formConfig, obj)
        this.formConfig.title = '编辑关联保司'
        this.formConfig.id = 1
        this.formConfig.show = true
    }
    // 编辑后清洗数据
    editAssociation(event: InsureCompanyOccupationDto) {
        const data = [] as DescItemDto[]
        for (const key in this.associationTemplate) {
            let value = null
            switch(key) {
            case 'insureCompanyCode':
                value = event.insureCompanyName
                break
            case 'highRisk':
                value = event.highRisk ? '是' : '否'
                break
            default:
                value = event[key as keyof typeof event]
            }
            data.push({
                ...this.associationTemplate[key],
                value: value,
                key: key
            })
        }
        this.association.push(data)
    }

    async initOccupationList() {
        const res = await queryCompanyOccupationListByOccupationId(this.curData.id)
        this.association = []
        this.occupationList = res
        res?.forEach(i => {
            this.editAssociation(i)
        })
    }

    render() {
        return (
            <>
                {/* {this.renderFilter()} */}
                <Drawer
                    v-model:show={this.showDrawer}
                    title="配置关联关系"
                    size="800px"
                    height="100%"
                    hideCancel={true}
                >
                    <div>
                        <div class="flex items-cente">
                            <InfoCircleOutlined style="font-weight: 600;" />
                            <div class="text-black-200 text-lg ml-8 font-semibold">系统信息</div>
                        </div>
                        <div class="mt-16 mb-24">
                            <RenderDescription
                                renderData={this.systemInfoData}
                                row={2}
                                size="middle"
                            />
                        </div>

                        {this.association.map((item, index) => {
                            return (
                                <>
                                    <div class="flex items-cente justify-between">
                                        <div class="flex items-center">
                                            <LinkOutlined style="font-weight: 600;" />
                                            <div class="text-black-200 text-lg ml-8 font-semibold">
                                                关联保司
                                            </div>
                                        </div>
                                        <div class="flex items-center text-base">
                                            <Button
                                                type="link"
                                                danger
                                                onClick={() => {
                                                    this.onDelAssociationItem(index)
                                                }}
                                            >
                                                删除
                                            </Button>
                                            <Button
                                                type="link"
                                                onClick={() => {
                                                    this.onEditInsuranceCompany(index)
                                                }}
                                            >
                                                编辑
                                            </Button>
                                        </div>
                                    </div>
                                    <div class="mt-16 mb-24">
                                        <RenderDescription
                                            renderData={item}
                                            row={2}
                                            size="middle"
                                        />
                                    </div>
                                </>
                            )
                        })}
                        <div class="flex items-center justify-between">
                            <div></div>
                            <Button
                                type="primary"
                                class="bg-blue-300 text-blue-100"
                                onClick={() => {
                                    this.onOpenAddAssociation()
                                }}
                            >
                                <PlusOutlined style="color:#3E5FF5;" />
                                添加关联保司
                            </Button>
                        </div>

                        {renderModal(this.formConfig)}
                    </div>
                </Drawer>
            </>
        )
    }
}

export default toNative<{ curData: InsureOccupationDto }, { change: () => void }>(
    EditInsuranceCompanyPop
)
